package com.tgy.jd.service;

import com.alibaba.fastjson.JSON;
import com.tgy.jd.entity.Content;
import com.tgy.jd.utils.HtmlParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.cluster.metadata.Metadata;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.core.TimeValue;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/***
 * @ClassName: ContentService
 * @Description:
 * @Auther: 送一一块二向箔
 * @Date: 16:21 2022/3/2
 * @version : V1.0
 */
@Slf4j
@Service
public class ContentService {
    public static void main(String[] args) {
        ContentService contentService = new ContentService();
        contentService.parseContext("java");
    }



    @Resource
    RestHighLevelClient restHighLevelClient;

    @Resource
    HtmlParseUtil htmlParseUtil;


    //解析数据放入索引中
    public Boolean parseContext(String keyword){
        ArrayList<Content> contents =null;
        if (Objects.equals(null,keyword)) {
            System.out.println("输入参数为空");
            log.info("输入参数为空");
            return false;
        }else {
            System.out.println("输入参数为："+keyword);
            contents = htmlParseUtil.parseJD(keyword);
        }

        //把查询好的数据放入ES
        BulkRequest bulkRequest = new BulkRequest();
        //设置超时2分钟
        bulkRequest.timeout("2m");

        for (int i = 0; i < contents.size(); i++) {
            bulkRequest.add(new IndexRequest("jd_goods")
                    .source(JSON.toJSONString(contents.get(i)), XContentType.JSON)
            );
        }


        BulkResponse bulk = null;
        try {
            bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES执行异常，报错信息：{}",e.getMessage());
            e.printStackTrace();
        }


        return !bulk.hasFailures();
    }



    //获取数据
    public ArrayList<Map<String, Object>> searchPage(String keyWord,int pageSize,int pageNum){
        if ((pageNum < 1)) {
            pageNum = 1;
        }
        if ((pageSize < 1)) {
            pageSize = 1;
        }


        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //这里使用模糊查询，不然两个中文搜不到
        //MatchQueryBuilder termQueryBuilder = QueryBuilders.matchQuery("name", keyWord);

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", keyWord);

        //分页
        searchSourceBuilder.from(pageNum);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));


        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = null;

        try {
             search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
             //不能关闭
            //restHighLevelClient.close();
        } catch (IOException e) {
            log.error("searchPage出错了{}",e.getMessage());
            e.printStackTrace();
        }


        //解析结果
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        SearchHits hits = search.getHits();
        for (SearchHit hit : hits.getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    //获取数据高亮
    public ArrayList<Map<String, Object>> searchPageHighlight(String keyWord,int pageSize,int pageNum){
        if ((pageNum < 1)) {
            pageNum = 1;
        }
        if ((pageSize < 1)) {
            pageSize = 1;
        }


        //条件搜索
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //这里使用模糊查询，不然两个中文搜不到
        MatchPhraseQueryBuilder termQueryBuilder = QueryBuilders.matchPhraseQuery("name", keyWord);
        //TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", keyWord);
        

        //分页
        searchSourceBuilder.from(pageNum);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        searchSourceBuilder.query(termQueryBuilder);
        searchSourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));

        // 高亮 =========
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false);//多个高亮显示
        highlightBuilder.field("name");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse search = null;

        try {
            search = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            //不能关闭
            //restHighLevelClient.close();
        } catch (IOException e) {
            log.error("searchPage出错了{}",e.getMessage());
            e.printStackTrace();
        }


        //解析结果

        ArrayList<Map<String, Object>> list = new ArrayList<>();
        SearchHits hits = search.getHits();
        for (SearchHit hit : hits.getHits()) {
            //解析高亮字段

            //获取高亮字段
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField name = highlightFields.get("name");
            //这里是原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //解析高亮字段 将原来的字段替换程高亮字段即可

            if (!Objects.equals(name,null)) {
                Text[] fragments = name.fragments();
                StringBuilder stringBuilder = new StringBuilder("");
                for (Text fragment : fragments) {
                    stringBuilder.append(fragment);
                }
                //替换字段
                sourceAsMap.put("name",stringBuilder);
            }
            list.add(sourceAsMap);
        }
        log.info("service searchPageHighlight 的出参为{}",list);
        return list;

    }
}
